package main

import (
	"bigmodel/internal/config"
	"database/sql"
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/golang-migrate/migrate/v4"
	"github.com/golang-migrate/migrate/v4/database/postgres"
	_ "github.com/golang-migrate/migrate/v4/source/file"
	_ "github.com/lib/pq"
	"github.com/zeromicro/go-zero/core/conf"
)

var (
	configFile = flag.String("f", "etc/bigmodel-api.yaml", "the config file")
	action     = flag.String("a", "", "the action to perform;up,down,goto,force,see")
	version    = flag.Int("v", 0, "the version")
)

func main() {
	flag.Parse()
	if *action == "" {
		fmt.Println("action is empty; \n Usage: migrate -a [upall|downall|goto|force|see] -v [version]")
		return
	}
	if *action == "force" && *version <= 0 {
		fmt.Println("force needs a version gt 0")
		return
	}

	var c config.Config
	conf.MustLoad(*configFile, &c)
	db, err := sql.Open("postgres", c.DB.DataSource)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	currentDir, _ := os.Getwd()
	driver, _ := postgres.WithInstance(db, &postgres.Config{})
	m, err := migrate.NewWithDatabaseInstance(
		fmt.Sprintf("file://%s/migrations/", currentDir),
		"aitools", driver)
	if err != nil {
		log.Fatal(err)
	}
	defer m.Close()
	switch *action {
	case "upall":
		err = m.Up()
		if err != nil {
			log.Fatalf("upall error: %v", err)
		}
	case "downall":
		err = m.Down()
		if err != nil {
			log.Fatalf("downall error: %v", err)
		}
	case "goto":
		err = m.Steps(*version)
		if err != nil {
			log.Fatalf("goto error: %v", err)
		}
	case "force":
		err = m.Force(*version)
		if err != nil {
			log.Fatalf("force error: %v", err)
		}
	case "see":
		v, isDirty, err := m.Version()
		if err != nil {
			log.Fatalf("see error: %v", err)
		}
		fmt.Println("current version:", v, "is dirty:", isDirty)
		return
	default:
		log.Fatalf("unknown action: %v", *action)
	}
}
